<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备件编号" prop="spareno">
            <el-input v-model="form.spareno" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="sparepartname">
            <el-input v-model="form.sparepartname" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型" prop="typename">
            <el-input v-model="form.typename" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌" prop="sparepartbrand">
            <el-select
              v-model="form.sparepartbrand"
              allow-create
              filterable
              default-first-option
              style="width: 300px"
              placeholder="请先选择品牌"
              :disabled="isView"
              @blur="onSubmitBrand"
            >
              <el-option
                v-for="(item, index) in sparepartbrandlist"
                :key="item.label + index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="型号" prop="spareparttmodel">
            <el-select
              v-model="form.spareparttmodel"
              allow-create
              filterable
              default-first-option
              placeholder="请先选择型号"
              style="width: 300px"
              :disabled="isView"
              @blur="onSubmitModelname"
            >
              <el-option
                v-for="(item, index) in sparepartmodellist"
                :key="item.label + index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="序列号">
            <el-input v-model="form.serialno" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备件归属">
            <el-input v-model="form.sparebelong" class="input_text" :readonly="isView" />
          </el-form-item>
          <el-form-item label="存放仓库" prop="warehouse">
            <el-select
              v-model="form.warehouse"
              allow-create
              filterable
              default-first-option
              style="width: 300px"
              placeholder="请选择仓库"
              :disabled="isView"
            >
              <el-option
                v-for="(item, index) in warehouseList"
                :key="item.id + index"
                :label="item.warehousename"
                :value="item.warehousename"
              />
            </el-select>
            <!--<el-input v-model="form.warehouse" />-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商">
            <el-input v-model="form.supplier" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--入库操作明细表格渲染-->
    <el-table v-if="isView" v-loading="loading" :data.sync="logList" size="small" height="250" style="width: 100%;">
      <!--<el-table-column prop="id" label="序号" />-->
      <el-table-column :show-overflow-tooltip="true" prop="retrievalTime" label="日期">
        <template slot-scope="scope">
          <span>{{ parseTimeShort(scope.row.retrievalTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="state" label="操作" :formatter="formateStateValue" />
      <el-table-column :show-overflow-tooltip="true" prop="purpose" label="用途" />
      <el-table-column :show-overflow-tooltip="true" prop="retrievalBy" label="操作人" />
      <el-table-column :show-overflow-tooltip="true" prop="notes" label="备注" />
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listWarehouse } from '@/api/tWarehouse'
import { add, edit } from '@/api/tSparepart'
import { getDictDetails, dictDetailAdd } from '@/api/dictDetail'
import { parseTime, parseTimeShort } from '@/utils/index'
import { queryLogs } from '@/api/tSparepartRetrieval'
import { formatState } from '@/constants/consts'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    },
    eqptId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      sparepartbrandlist: [],
      sparepartmodellist: [],
      warehouseList: [],
      title: '',
      form: {
        id: '',
        eqpt_id: '',
        spareno: '',
        sparepartname: '',
        typename: '',
        sparepartbrand: '',
        spareparttmodel: '',
        serialno: '',
        sparebelong: '',
        warehouse: '',
        supplier: '',
        stock_by: '',
        stock_time: '',
        stocknum: '',
        state: ''
      },
      rules: {
        spareno: [
          { required: true, message: '请输入备件编号', trigger: 'blur' }
        ],
        sparepartname: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        typename: [{ required: true, message: '请输入类型', trigger: 'blur' }],
        sparepartbrand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
        spareparttmodel: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ],
        warehouse: [
          { required: true, message: '请输入存放仓库', trigger: 'blur' }
        ]
      },
      logList: []
    }
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 200px'
    } else {
      this.style = 'width: 172px'
    }
  },
  mounted: function() {
    const that = this
    listWarehouse().then(res => {
      that.warehouseList = res.content
    }).catch(err => {
      console.log(err)
    })
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    parseTimeShort,
    onSubmitBrand(event) {
      const label = event.target.value
      if (label.length > 0) {
        let maxValue = 0
        let needadd = true
        for (var index in this.sparepartbrandlist) {
          const obj = this.sparepartbrandlist[index]
          console.log(obj)
          if (obj.label === label) {
            needadd = false
            break
          }
          if (parseInt(obj.value) > maxValue) {
            maxValue = parseInt(obj.value)
          }
        }
        if (needadd) {
          var data = { id: '', label: this.form.sparepartbrand, value: maxValue + 1, sort: 999, dict: { id: 18 }}
          dictDetailAdd(data)
            .then(res => {
              this.$notify({
                title: '添加成功',
                type: 'success',
                duration: 2500
              })
            })
            .catch(err => {
              this.loading = false
              console.log(err)
            })
        } // end of need add
      }
    },
    onSubmitModelname(event) {
      const label = event.target.value
      if (label.length > 0) {
        let maxValue = 0
        let needadd = true
        for (var index in this.sparepartmodellist) {
          const obj = this.sparepartmodellist[index]
          if (obj.label === label) {
            needadd = false
            break
          }
          if (parseInt(obj.value) > maxValue) {
            maxValue = parseInt(obj.value)
          }
        }
        if (needadd) {
          var data = {
            id: '',
            label: this.form.spareparttmodel,
            value: maxValue + 1,
            sort: 999,
            dict: { id: 17 }
          }
          dictDetailAdd(data)
            .then(res => {
              this.$notify({
                title: '添加成功',
                type: 'success',
                duration: 2500
              })
            })
            .catch(err => {
              this.loading = false
              console.log(err)
            })
        }
      }
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      if (this.eqptId > 0) {
        this.form['eqpt_id'] = this.eqptId
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        }
      })
    },
    doAdd() {
      add(this.form)
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.$parent.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    doEdit() {
      this.form.stock_time = parseTime(this.form.stock_time)

      edit(this.form)
        .then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.supThis.init()
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        spareno: '',
        sparepartname: '',
        typename: '',
        sparepartbrand: '',
        spareparttmodel: '',
        serialno: '',
        sparebelong: '',
        warehouse: '',
        supplier: '',
        stock_by: '',
        stock_time: '',
        stocknum: '',
        state: ''
      }
    },
    getSparepartBrand() {
      getDictDetails('sparepart_brand').then(res => {
        this.sparepartbrandlist = res.content
      })
    },
    getSpareparttmodel() {
      getDictDetails('sparepart_modelname').then(res => {
        this.sparepartmodellist = res.content
      })
    },
    getQueryLogs(id) {
      queryLogs(id).then(res => {
        this.logList = res.content
      }).catch(err => {
        console.log(err)
        this.logList = []
      })
    },
    // 返回状态值
    formateStateValue(row) {
      return formatState(row['state'])
    }
  }// endf of methods
}
</script>

<style scoped>
.input_text {
  width: 300px;
}
</style>
